#include "stdlib.h"
#include "ctype.h"
#include "scheduler.h"

static unsigned long _rand_next = 1;

static int get_cmos_int(int reg);
static int set_cmos_int(int reg, int value);


long int
atol (const char *string)
{
	long int n;
	unsigned int i=0, isNegative;

	isNegative = 0;
	while (isspace(string[i]))
		i++;
	if (string[i] == '+')
		i++;
	if (string[i] == '-')
	{
		i++;
		isNegative = 1;
	}

	for (n = 0; isdigit(string[i]); i++)
		n = n * 10 + (string[i] - '0');

	return (isNegative ? -n : n);
}

int
atoi (const char *string)
{
	return atol(string);
}

int
abs (int number)
{
	return (number < 0 ? -number : number);
}

long int
labs (long int number)
{
	return (number < 0 ? -number : number);
}

/*
 * Implementation notes:
 * POSIX 1003.1-2003 gives the following example of an implementation of
 * rand() and srand(), possibly useful when one needs the same sequence on
 * two different machines.
 * RAND_MAX assumed to be 32767.
 */

int
rand(void)
{
	_rand_next = _rand_next * 1103515245 + 12345;
	return ((unsigned) (_rand_next / 65536) % 32768);
}

void
srand(unsigned seed)
{
	_rand_next = seed;
}

long int
time(long int *result)
{
	int year, month, day, hour, min, sec;
	long int t, days;

	/* ANDY 06/08/2006: Reemplac� get_cmos_time por gettime */
	if (!gettime(&year, &month, &day, &hour, &min, &sec))
		return (-1);

	days = (year - 1970) * 365 + (month - 1) * 30 + (day - 1);
	t = ((days * 24 + hour) * 60 + min) * 60 + sec;

	if (result != NULL)
		*result = t;
	return t;
}

int
gettime(int *year, int *month, int *day, int *hour, int *min, int *sec)
{
	*year = 100 * get_cmos_int(0x32) + get_cmos_int(0x09);
	*month = get_cmos_int(0x08);
	*day = get_cmos_int(0x07);
	*hour = get_cmos_int(0x04);
	*min = get_cmos_int(0x02);
	*sec = get_cmos_int(0x00);
	return 1;
}

int
settime(int year, int month, int day, int hour, int min, int sec)
{
	set_cmos_int(0x32, year / 100);
	set_cmos_int(0x09, year % 100);
	set_cmos_int(0x08, month);
	set_cmos_int(0x07, day);
	set_cmos_int(0x04, hour);
	set_cmos_int(0x02, min);
	set_cmos_int(0x00, sec);
	return 1;
}

static int
get_cmos_int(int reg)
{
	int bcd;
	bcd = readcmos(reg);
	return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F));
}

static int
set_cmos_int(int reg, int value)
{
	int bcd;
	bcd = (((value / 10) % 10) << 4) + (value % 10);
	return writecmos(value % 100, reg);
}

void *
malloc(int size)
{
	return incCurrHeap(size, 0);
}

void*
Calloc(int size)
{
	char* temp;
	int i;

	temp = (char*)malloc(size);

	if(temp != NULL)
	{
		for(i=0;i<size;i++)
			temp[i]=0;
	}

	return (void*)temp;
}
